package com.abc.thread;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadMian {


   public static void main(String[] args) throws Exception {

      ThreadPoolTaskExecutor rechargeTaskExecutor = new ThreadPoolTaskExecutor();
      // 设置核心线程数
      rechargeTaskExecutor.setCorePoolSize(5);
      // 设置最大线程数
      rechargeTaskExecutor.setMaxPoolSize(5);
      // 设置队列容量
      rechargeTaskExecutor.setQueueCapacity(2);
      // 设置允许的空闲时间（秒）
      rechargeTaskExecutor.setKeepAliveSeconds(60);
      // 设置默认线程名称
      rechargeTaskExecutor.setThreadNamePrefix("or-task-");
      // 设置拒绝策略rejection-policy：当pool已经达到max size的时候，如何处理新任务
      // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
      rechargeTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
//      rechargeTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
      // 等待所有任务结束后再关闭线程池
      rechargeTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);

      rechargeTaskExecutor.initialize();

      System.out.println("activeCount前" + rechargeTaskExecutor.getActiveCount());

      CountDownLatch latch = new CountDownLatch(10);

      Long start = System.currentTimeMillis();

      List<WorkThread> workThreads = new ArrayList<>();

      for (int i = 0; i < 10; i++) {

         WorkThread workThread = new WorkThread();
         workThread.setLatch(latch);
         workThread.setIndex(i);
         workThread.setStart(System.currentTimeMillis());

         workThreads.add(workThread);
         rechargeTaskExecutor.execute(workThread);
      }

      System.out.println("activeCount后" + rechargeTaskExecutor.getActiveCount());

      latch.await(2000, TimeUnit.MILLISECONDS);

      for (WorkThread wk : workThreads) {
         wk.setExit(true);
      }
      Long end = System.currentTimeMillis();

      System.out.println("activeCount awit 后" + rechargeTaskExecutor.getActiveCount());


      System.out.println("主线程执行后面,耗时=" + (end - start));

   }

//      new Thread().start();

}
